package edu.washington.ling.syntric.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XMLUtils {
	public static Document readXMLFile(String fileName) throws IOException {
		Document doc = null;
		File file = new File(fileName);
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			docBuilderFactory.setFeature("http://apache.org/xml/features/allow-java-encodings", 
			          true);
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			doc = docBuilder.parse(file);
			doc.normalize();
		} 
		catch (SAXException e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		} 
		catch (ParserConfigurationException e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		}
		return doc;
	}
	public static void writeXMLFile(Document doc, String fileName) throws IOException {
		try {
			TransformerFactory xformFactory = TransformerFactory.newInstance();
			xformFactory.setAttribute("indent-number", new Integer(2));
			Transformer xform = xformFactory.newTransformer();
			xform.setOutputProperty(OutputKeys.INDENT, "yes");
			Source source = new DOMSource(doc);
			Writer writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(fileName), "UTF8"));
			Result result = new StreamResult(writer);
			xform.transform(source, result);
			writer.flush();
			writer.close();
		}
		catch(TransformerConfigurationException e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		}
		catch(TransformerException e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}
}
